﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using ERP_RORZE_SYSTEM;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ERP_RORZE_DLL.Assembly
{
    public partial class frm_Add_F5AssemblyWTS : Form
    {
        private string addEdit;
        private int id;
        public string AddEdit
        {
            get { return addEdit; }
            set { addEdit = value; }
        }

        public frm_Add_F5AssemblyWTS()
        {
            InitializeComponent();
            this.mySetting = new INISettings();
            this.myConnection = new SqlConnection(mySetting.SQLConnectionString);
            this.addDate.EditValue = DateTime.Now.Date;
            getStaffList();
            this.staffID.Properties.AutoComplete = true;            
            getWorkIDList();
            this.timeworkID.Properties.AutoComplete = true;
            getOrderNoList();
            this.orderNo.Properties.AutoComplete = true;
            this.addDate.EditValue = DateTime.Now.Date.AddDays(-1);
            this.timeworkID.LostFocus += timeworkID_LostFocus;
        }

        void timeworkID_LostFocus(object sender, EventArgs e)
        {
            if (addEdit == "Add")
            {
                ComboboxItem item = new ComboboxItem();
                bool check = true;
                string enter_text = this.timeworkID.Text.Trim();
                string sub_text = null;
                string main_text = null;
                if (enter_text.Length == 5)
                {
                    check = false;
                    main_text = enter_text.Substring(0, 4);
                    sub_text = enter_text.Substring(4, 1);

                    for (int i = 0; i < this.timeworkID.Properties.Items.Count; i++)
                    {
                        item = (ComboboxItem)this.timeworkID.Properties.Items[i];
                        if (item.Value.ToString() == main_text)
                        {
                            check = true;
                            this.timeworkID.SelectedIndex = i;
                            this.compType.Text = sub_text;
                        }
                    }
                }
                else
                {
                    check = false;
                    main_text = enter_text;
                    for (int i = 0; i < this.timeworkID.Properties.Items.Count; i++)
                    {
                        item = (ComboboxItem)this.timeworkID.Properties.Items[i];
                        if (item.Value.ToString() == main_text)
                        {
                            check = true;
                            this.timeworkID.SelectedIndex = i;
                            this.compType.Text = sub_text;
                        }
                    }
                }

                if (!check)
                {
                    MessageBox.Show("Invalid Time Work ID");
                    this.timeworkID.SelectedIndex = -1;
                }
            }
        }
        
        ////////////////////////////////////////////////
        /// Load Order No list to form
        ////////////////////////////////////////////////
        private void getOrderNoList()
        {
            try
            {
                myConnection.Open();
                SqlCommand cmd_sql = myConnection.CreateCommand();
                cmd_sql.CommandText = "SELECT OrderNo, PartNo, CommandQuantity, FinishedDate"
                    + " FROM [231_F5Plan] WHERE (FinishedDate IS NULL) Or (DATEDIFF(day,FinishedDate,GETDATE())<30) ORDER BY OrderNo";
                SqlDataReader dataReader = cmd_sql.ExecuteReader();
                while (dataReader.Read())
                {
                    string part_no = null;
                    string finished_date = null;
                    if (dataReader["PartNo"] != DBNull.Value)
                    {
                        part_no = " | " + dataReader["PartNo"].ToString();
                    }
                    /*
                    if (dataReader["FinishedDate"] != DBNull.Value)
                    {
                        finished_date = " | " + DateTime.Parse(dataReader["FinishedDate"].ToString()).ToShortDateString();
                    }
                     */
                    ComboboxItem item = new ComboboxItem();
                    item.Text = dataReader["OrderNo"].ToString() + part_no + finished_date;                    
                    item.Value = dataReader["OrderNo"].ToString();
                    this.orderNo.Properties.Items.Add(item);
                }
                dataReader.Close();
                cmd_sql.Dispose();
                myConnection.Close();
            }
            catch (Exception ex)
            {
                if (myConnection.State == ConnectionState.Open)
                {
                    myConnection.Close();
                }
                MessageBox.Show(ex.Message);
                //MessageBox.Show("Cannot get OrderNo list");
            }
        }

        ////////////////////////////////////////////////
        /// Load Staff list to form
        ////////////////////////////////////////////////
        private void getStaffList()
        {
            try
            {
                myConnection.Open();
                SqlCommand cmd_sql = myConnection.CreateCommand();
                cmd_sql.CommandText = "SELECT StaffID, StaffName FROM [222_Staff]"
                    + " WHERE (([DepartmentID] = '231') OR ([DepartmentID] = '232')) AND (StopDate IS NULL)"
                    + " ORDER BY StaffName";
                SqlDataReader dataReader = cmd_sql.ExecuteReader();
                while (dataReader.Read())
                {
                    ComboboxItem item = new ComboboxItem();
                    item.Text = dataReader["StaffID"].ToString() + " | " + dataReader["StaffName"].ToString();
                    item.Value = dataReader["StaffID"].ToString();
                    this.staffID.Properties.Items.Add(item);
                }
                dataReader.Close();
                cmd_sql.Dispose();
                myConnection.Close();
            }
            catch
            {
                if (myConnection.State == ConnectionState.Open)
                {
                    myConnection.Close();
                }
                MessageBox.Show("Cannot get Staff list");
            }
        }

        ////////////////////////////////////////////////
        /// Load WorkID list to form
        ////////////////////////////////////////////////
        private void getWorkIDList()
        {
            try
            {
                myConnection.Open();
                SqlCommand cmd_sql = myConnection.CreateCommand();
                cmd_sql.CommandText = "SELECT TimeWorkID, TimeWorkName FROM [231_TimeWork] ORDER BY TimeWorkName";
                SqlDataReader dataReader = cmd_sql.ExecuteReader();
                while (dataReader.Read())
                {
                    ComboboxItem item = new ComboboxItem();
                    item.Text = dataReader["TimeWorkID"].ToString();// +" | " + dataReader["TimeWorkName"].ToString();
                    item.Value = dataReader["TimeWorkID"].ToString();
                    this.timeworkID.Properties.Items.Add(item);
                }
                dataReader.Close();
                cmd_sql.Dispose();
                myConnection.Close();
            }
            catch
            {
                if (myConnection.State == ConnectionState.Open)
                {
                    myConnection.Close();
                }
                MessageBox.Show("Cannot get TimeWorkID list");
            }
        }

        private void buttonCancel_Click(object sender, EventArgs e)
        {
            this.Dispose();
        }        
        
        ///////////////////////////
        /// When Click Add Button
        ///////////////////////////        
        private void buttonAdd_Click(object sender, EventArgs e)
        {
            try
            {
                if (buttonAdd.Text == "Edit")
                {
                    buttonAdd.Text = "Update";
                    DataRow row = this.gvWTSDetailByID.GetFocusedDataRow();
                    this.id = Int32.Parse(row[0].ToString());
                    for (int i = 0; i < this.timeworkID.Properties.Items.Count; i++)
                    {
                        ComboboxItem item = (ComboboxItem)this.timeworkID.Properties.Items[i];
                        if (row[4].ToString() == item.Text.ToString())
                        {
                            this.timeworkID.SelectedIndex = i;
                        }
                    }

                    for (int i = 0; i < this.orderNo.Properties.Items.Count; i++)
                    {
                        ComboboxItem item = (ComboboxItem)this.orderNo.Properties.Items[i];
                        if (row[3].ToString() == item.Value.ToString())
                        {
                            this.orderNo.SelectedIndex = i;
                        }
                    }
                    this.timeValue.Text = row[7].ToString();
                    this.quantityValue.Text = row[8].ToString();
                    this.noteText.Text = row[9].ToString();
                }
                else
                {
                    string error = null;
                    ComboboxItem staff_id = new ComboboxItem();
                    ComboboxItem timework_id = new ComboboxItem();
                    ComboboxItem order_no = new ComboboxItem();
                    if (string.IsNullOrEmpty(error))
                    {
                        if (this.addDate.EditValue == null)
                        {
                            error = "Please select Date";
                        }
                    }

                    if (string.IsNullOrEmpty(error))
                    {
                        if (this.staffID.SelectedIndex == -1)
                        {
                            error = "Please select Staff";
                        }
                    }

                    if (string.IsNullOrEmpty(error))
                    {
                        if (this.timeworkID.SelectedIndex == -1)
                        {
                            error = "Please select Work ID";
                        }
                    }

                    if (string.IsNullOrEmpty(error))
                    {
                        if (this.orderNo.SelectedIndex == -1)
                        {
                            error = "Please select Order No";
                        }
                    }

                    float time_value = 0;
                    if (string.IsNullOrEmpty(error))
                    {
                        bool check_time = float.TryParse(this.timeValue.Text, out time_value);
                        if (!check_time)
                        {
                            error = "Invalid time value";
                        }
                        else
                        {
                            if (time_value <= 0)
                            {
                                error = "Time value must be greater than 0";
                            }
                        }
                    }

                    if (string.IsNullOrEmpty(error))
                    {
                        staff_id = (ComboboxItem)this.staffID.SelectedItem;
                        timework_id = (ComboboxItem)this.timeworkID.SelectedItem;
                        order_no = (ComboboxItem)this.orderNo.SelectedItem;
                        if ((timework_id.Value.ToString().Trim().ToUpper() == "KC61") || (timework_id.Value.ToString().Trim().ToUpper() == "KC71"))
                        {
                            if (string.IsNullOrEmpty(this.noteText.Text))
                            {
                                error = "The Time Work: " + timework_id.Text + " requires Remark";
                            }
                        }
                    }

                    if (string.IsNullOrEmpty(error))
                    {
                        if (orderNo.Text.Count(char.IsSymbol) > 1)
                        {
                            if (Convert.ToDateTime(addDate.EditValue) > Convert.ToDateTime(orderNo.Text.Substring(order_no.Text.LastIndexOf("|") + 2)))
                            {
                                if (string.IsNullOrEmpty(this.noteText.Text))
                                {
                                    error = "The Input date can not greater than finish date.";
                                }
                            }
                        }
                    }

                    if (string.IsNullOrEmpty(error))
                    {
                        try
                        {
                            DateTime inputdate;
                            DateTime.TryParse(this.addDate.DateTime.Date.ToString(), out inputdate);
                            myConnection.Open();
                            string sql = "";
                            if (addEdit == "Add")
                            {
                                sql = "INSERT INTO [231_TimeInput] (Date, StaffID, TimePlanNo, TimeWorkID, AssemblyTime,"
                                    + " ActualQuantity, Note, CompType, F5)"
                                    + " VALUES (@dateinput, '" + staff_id.Value.ToString() + "', '" + order_no.Value.ToString() + "',"
                                    + " '" + timework_id.Value.ToString() + "', " + time_value + ", '" + this.quantityValue.Text + "',"
                                    + " N'" + this.noteText.Text + "', '" + this.compType.Text + "', 1)";
                            }
                            else
                            {
                                sql = "UPDATE [231_TimeInput] SET Date=@dateinput, StaffID='" + staff_id.Value.ToString() + "', TimePlanNo='"
                                    + order_no.Value.ToString() + "', TimeWorkID='" + timework_id.Value.ToString() + "', AssemblyTime='"
                                    + time_value + "', ActualQuantity='" + this.quantityValue.Text + "', Note= N'" + this.noteText.Text + "', CompType='"
                                    + this.compType.Text + "', F5=1 WHERE ID=" + this.id;
                            }
                            SqlCommand cmd_sql = new SqlCommand(sql, myConnection);
                            cmd_sql.Parameters.Add("@dateinput", SqlDbType.DateTime).Value = inputdate.Date;
                            cmd_sql.ExecuteNonQuery();
                            cmd_sql.Dispose();
                            myConnection.Close();
                            //MessageBox.Show("F5 WTS added success.");
                            LoadData();
                            if (addEdit == "Add")
                            {
                                clearForm();
                                this.staffID.Focus();
                            }
                            else
                            {
                                buttonAdd.Text = "Edit";
                                this.staffID.Focus();
                            }
                        }
                        catch (Exception ex)
                        {
                            if (myConnection.State == ConnectionState.Open)
                            {
                                myConnection.Close();
                            }
                            MessageBox.Show(ex.Message);
                            //MessageBox.Show("Cannot add F5 WTS. Please try again.");
                        }
                    }
                    else
                    {
                        MessageBox.Show(error);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void LoadData()
        {
            ComboboxItem staff_id = new ComboboxItem();
            gridWTSDetailByID.DataSource = null;
            gvWTSDetailByID.Columns.Clear();
            DataSet sourceDataSet = new DataSet();
            staff_id = (ComboboxItem)this.staffID.SelectedItem;
            string sql = "SELECT [231_TimeInput].ID, [231_TimeInput].Date, [222_Staff].StaffName, [231_TimeInput].TimePlanNo,"
                + " [231_TimeInput].TimeWorkID, [231_TimeWork].TimeWorkName, [231_TimeInput].CompType, [231_TimeInput].AssemblyTime,"
                + " [231_TimeInput].ActualQuantity, [231_TimeInput].Note"
                + " FROM [231_TimeInput] LEFT OUTER JOIN"
                + " [222_Staff] ON [231_TimeInput].StaffID=[222_Staff].StaffID LEFT OUTER JOIN"
                + " [231_TimeWork] ON [231_TimeInput].TimeWorkID=[231_TimeWork].TimeWorkID"
                + " WHERE [231_TimeInput].Date=@WTSDate AND [231_TimeInput].StaffID=@StaffID AND [231_TimeInput].F5 = 1"
                + " ORDER BY [231_TimeInput].ID DESC";
            myConnection.Open();
            SqlCommand cmd_sql = new SqlCommand(sql, myConnection);
            SqlDataAdapter adapter = new SqlDataAdapter();
            adapter.SelectCommand = cmd_sql;
            cmd_sql.Parameters.Add("@WTSDate", SqlDbType.DateTime).Value = DateTime.Parse(this.addDate.EditValue.ToString());
            cmd_sql.Parameters.Add("@StaffID", SqlDbType.VarChar).Value = staff_id.Value.ToString();
            adapter.Fill(sourceDataSet);
            adapter.Dispose();
            cmd_sql.Dispose();
            myConnection.Close();
            if (sourceDataSet != null)
            {
                gridWTSDetailByID.DataSource = sourceDataSet.Tables[0];
            }
            else
            {
                DataTable newTable = new DataTable();
                newTable.Columns.Add("ID", typeof(int));
                newTable.Columns.Add("Date", typeof(DateTime));
                newTable.Columns.Add("Staff", typeof(string));
                newTable.Columns.Add("TimePlanNo", typeof(string));
                newTable.Columns.Add("TimeWorkID", typeof(string));
                newTable.Columns.Add("TimeWorkName", typeof(string));
                newTable.Columns.Add("CompType", typeof(string));
                newTable.Columns.Add("AssemblyTime", typeof(int));
                newTable.Columns.Add("ActualQuantity", typeof(int));
                newTable.Columns.Add("Note", typeof(string));
                gridWTSDetailByID.DataSource = newTable;
            }
            gvWTSDetailByID.Columns[0].Caption = "ID";
            gvWTSDetailByID.Columns[1].Caption = "Date";
            gvWTSDetailByID.Columns[2].Caption = "Person";
            gvWTSDetailByID.Columns[3].Caption = "Order No";
            gvWTSDetailByID.Columns[4].Caption = "Time Work ID";
            gvWTSDetailByID.Columns[5].Caption = "Time Work Name";
            gvWTSDetailByID.Columns[6].Caption = "Comp Type";
            gvWTSDetailByID.Columns[7].Caption = "F5 Time";
            gvWTSDetailByID.Columns[8].Caption = "Number";
            gvWTSDetailByID.Columns[9].Caption = "Remark";
            gvWTSDetailByID.Columns[0].Visible = false;
            gvWTSDetailByID.Columns[1].Visible = false;
            gvWTSDetailByID.Columns[2].Visible = false;
            gvWTSDetailByID.Columns[7].SummaryItem.SummaryType = DevExpress.Data.SummaryItemType.Sum;
            gvWTSDetailByID.Columns[7].SummaryItem.DisplayFormat = "Total: {0}";
            gvWTSDetailByID.BestFitColumns();
        }

        private void clearForm()
        {
            foreach (Control c in this.Controls)
            {
                if (c.Name != "staffID" && c.Name !="addDate")
                {
                    if (c is System.Windows.Forms.ComboBox)
                    {
                        ((System.Windows.Forms.ComboBox)c).SelectedIndex = -1;
                    }

                    if (c is System.Windows.Forms.TextBox)
                    {
                        ((System.Windows.Forms.TextBox)c).Text = null;
                    }

                    if (c is DevExpress.XtraEditors.TextEdit)
                    {
                        ((DevExpress.XtraEditors.TextEdit)c).Text = null;
                    }

                    if (c is DevExpress.XtraEditors.ComboBoxEdit)
                    {
                        ((DevExpress.XtraEditors.ComboBoxEdit)c).SelectedIndex = -1;
                    }

                    if (c is System.Windows.Forms.MaskedTextBox)
                    {
                        ((System.Windows.Forms.MaskedTextBox)c).Text = null;
                    }
                }
            }
        }

        private void staffID_SelectedValueChanged(object sender, EventArgs e)
        {
            try
            {
                LoadData();
            }
            catch //(Exception ex)
            {
                MessageBox.Show("Please input StaffID!");
            }
        }

        private void timeValue_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                buttonAdd_Click(sender,e);
            }
        }

        private void gvWTSDetailByID_RowCountChanged(object sender, EventArgs e)
        {

            if (addEdit == "Add")
            {
            }
            else
            {
                if (gvWTSDetailByID.RowCount > 0)
                {
                    buttonAdd.Enabled = true;
                }
                else
                {
                    buttonAdd.Enabled = false;
                }
            }
        }

        private void frm_Add_F5AssemblyWTS_Load(object sender, EventArgs e)
        {
            if (this.addEdit == "Add")
            {
                this.buttonAdd.Text = "Add";
                this.Text = "Add F5 WorkTimeSheet";
                labelControl8.Text = "Add F5 WorkTimeSheet";
            }
            else
            {
                this.buttonAdd.Text = "Edit";
                this.Text = "Edit F5 WorkTimeSheet";
                labelControl8.Text = "Edit F5 WorkTimeSheet";
            }
        }
    }
}
